package com.honour.controller.interfaced;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.honour.service.interfaced.CartInManager;
import com.honour.service.interfaced.ProductInManager;
import com.system.controller.base.BaseController;
import com.system.util.AppUtil;
import com.system.util.PageData;
import com.system.util.Tools;

/**
 * 购物车接口
 * 
 * @Function
 * @Author zhaozhenhua
 * @Date 2018年1月24日
 */
@Controller
@RequestMapping(value = "/appcartin")
public class CartInController extends BaseController {

	@Resource(name = "cartInService")
	private CartInManager cartInService;
	
	@Resource(name="proInService")
	private ProductInManager productInService;

	/**
	 * 添加商品到购物车
	 * 
	 * @Author zhanglingbing
	 * @date 2018年2月2日
	 * @return
	 */
	@RequestMapping(value = "/addcart")
	@ResponseBody
	public Object addCart() {
		logBefore(logger, "添加商品到购物车");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		logBefore(logger, pd.toString());
		String result = "00";
		try {
			if (Tools.checkKey("ADDCART", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("addCart", pd)) { // 检查参数
					//通过规格id查询商品信息
					PageData standardInfo = productInService.selectByStandardId(pd);
					//将查询出来的商品id赋值给pd
					pd.put("PRODUCT_ID", standardInfo.get("PRODUCT_ID"));
					PageData product = productInService.selectProByProId(pd);
					//将查询出来的商家id赋值给pd
					String businessId = (String) product.get("BUSINESS_ID");
					pd.put("BUSINESS_ID", businessId);
					//查询添加的商品购物车中是否存在
					PageData cart = cartInService.selectCartByDoubleId(pd);
					if (cart != null) {//修改购物车里的商品数量
						Integer num = (Integer) cart.get("QUANTITY");
//						logBefore(logger, num.toString());
						pd.put("QUANTITY", num+Integer.parseInt(pd.getString("QUANTITY")));
						pd.put("CART_ID", cart.get("CART_ID"));
//						logBefore(logger, pd.get("QUANTITY").toString());
						cartInService.update(pd);
						result = "01";
					} else {//是不是还要通过商品id查询出商家id
						
						//购物车id
						pd.put("CART_ID", this.getSnowId());
						//默认为选择
						pd.put("CHECKED", "1");
						cartInService.save(pd);
						// 返回01为创建成功并返回
						result = "01";
					}
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * 删除购物车
	 * 
	 * @Author zhanglingbing
	 * @date 2018年1月29日
	 * @return
	 *
	 */
	@RequestMapping(value = "/deletecart")
	@ResponseBody
	public Object deleteCart() {
		logBefore(logger, "删除购物车");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("DELETECART", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("deleteCart", pd)) { // 检查参数
					String cardIdArr = (String) pd.get("CART_ID");
					String[] cardId = cardIdArr.split(",");
					int num = 0 ;
					for (int i = 0; i < cardId.length; i++) {
						pd.put("CART_ID", cardId[i]);
						logBefore(logger, cardId[i]);
						cartInService.delete(pd);
						num++;
					}
					// 返回01为删除成功并返回
					result = (num == cardId.length)?"01" : "02";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * 修改购物车(购物车商品规格修改)
	 * 
	 * @Author zhanglingbing
	 * @date 2018年1月29日
	 * @return
	 *
	 */
	@RequestMapping(value = "/updatecart")
	@ResponseBody
	public Object updateCart() {
		logBefore(logger, "修改购物车");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("UPDATECART", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("updateCart", pd)) { // 检查参数
					//查询商品改变的规格id并将其赋值 给pd,然后修改购物车信息
					//PageData standard = cartInService.selectStandardIdAndPrice(pd);
					/*if (standard != null) {
						pd.put("STANDARD_ID", standard.get("STANDARD_ID"));
						logBefore(logger, pd.get("STANDARD_ID").toString());
					}*/
					//这里修改的是cart中的数量以及关联的规格id
					cartInService.update(pd);
					
					//修改成功之后,将此件商品的相关信息返回
					
					// 返回01为修改成功并返回
					result = "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * 根据用户id查询购物车列表
	 * 
	 * @Author zhanglingbing
	 * @date 2018年1月29日
	 * @return
	 *
	 */
	@RequestMapping(value = "/cartlist")
	@ResponseBody
	public Object selectCartByUserId() {
//		ServletUtil.SetHttpServletResponse(response);
		logBefore(logger, "根据用户id查询购物车列表");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("SELCAUS", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("selectCartByUserId", pd)) { // 检查参数
					List<PageData> list = cartInService.selectCartListInfo(pd);
					
					map.put("pd", list);
					result = (null == list) ? "02" : "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * 根据用户id从购物车移除商品(未用)
	 * 
	 * @Author zhanglingbing
	 * @date 2018年1月29日
	 * @return
	 *
	 */
	@RequestMapping(value = "/delproincart")
	@ResponseBody
	public Object deleteProductIds() {
		logBefore(logger, "根据用户id从购物车移除商品");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("DELETEPRODUCTIDS", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("deleteProductIds", pd)) { // 检查参数
					cartInService.deleteProductIds(pd);
					result = "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * 根据用户id修改购物车已选或未选(暂时不用)
	 * 
	 * @Author zhanglingbing
	 * @date 2018年1月30日
	 * @return
	 *
	 */
	@RequestMapping(value = "/updprochecked")
	@ResponseBody
	public Object updProChecked() {
		logBefore(logger, "根据用户id修改购物车已选或未选");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("UPDPROCHECKED", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("updProChecked", pd)) { // 检查参数
					cartInService.updProChecked(pd);
					result = "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * 根据用户id查询已选购物车商品总数
	 * 
	 * @Author zhanglingbing
	 * @date 2018年1月30日
	 * @return
	 *
	 */
	@RequestMapping(value = "/cartproallcount")
	@ResponseBody
	public Object selectCartProAllCount() {
		logBefore(logger, "根据用户id查询已选购物车商品总数");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("SELECTCARTPROALLCOUNT", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("selectCartProAllCount", pd)) { // 检查参数
					Integer count = cartInService.selectCartProAllCount(pd);
					map.put("pd", count);
					result = "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * 根据用户id和商品id查询是否已存在该商品的购物车 
	 * 
	 * @Author zhanglingbing
	 * @date 2018年1月30日
	 * @return
	 *
	 */
	@RequestMapping(value = "/proincart")
	@ResponseBody
	public Object selectCartByDoubleId() {
		logBefore(logger, "根据用户id和商品id查询是否已存在该商品的购物车 ");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("SELECTCARTBYDOUBLEID", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("selectCartByDoubleId", pd)) { // 检查参数
					PageData selectCartByDoubleId = cartInService.selectCartByDoubleId(pd);
					map.put("pd", selectCartByDoubleId);
					result = (selectCartByDoubleId==null)?"02":"01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * 根据用户id和选择状态查询商品(购物车结算可用)
	 * @Author zhanglingbing
	 * @date 2018年1月30日
	 * @return
	 *
	 */
	@RequestMapping(value = "/settlement")
	@ResponseBody
	public Object selectProductByUserIdAndChecked() {
		logBefore(logger, "根据用户id和选择状态查询商品(购物车结算可用)");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("SETTLEMENT", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("selectProductByUserIdAndChecked", pd)) { // 检查参数
					List<PageData> productList = cartInService.selectProductByUserIdAndChecked(pd);
					map.put("pd", productList);
					result = (productList==null)?"02":"01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 获取购物车列表
	 * @Author zhanglingbing
	 * @date 2018年1月30日
	 * @return 购物车id,商家名称,商品名称,商品价格,商品原价,商品配送方式,商品状态,商品规格,商品数量,商品显示图地址
	 *
	 */
	@RequestMapping(value = "/cartinfo")
	@ResponseBody
	public Object selectCartListInfo() {
		logBefore(logger, "获取购物车列表");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("SELECTCARTLISTINFO", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("selectCartListInfo", pd)) { // 检查参数
					List<PageData> cartList = cartInService.selectCartListInfo(pd);
//					Map<Integer, Map<Map<String, String>,  Map<String, PageData[]>>> cart = new HashMap<>();
					Map<Integer, Object[]> cart = new HashMap<>();
					Set<String> name = new HashSet<>();
					List<String> nameNum = new ArrayList<>();
					
					logBefore(logger,cartList.size()+"");
					
					//获取购物车列表时将所有的选择状态置为0(不勾选状态)
					for (PageData cartInfo : cartList) {
						String shopName1 = (String) cartInfo.get("SHOPNAME");
						name.add(shopName1);
						nameNum.add(shopName1);
						String checked = (String) cartInfo.get("CHECKED");
//						logBefore(logger, checked);
						pd.put("CART_ID", cartInfo.get("CART_ID"));
						if ("1".equals(checked)) {
							pd.put("CHECKED", "0");
							cartInService.updProChecked(pd);
							cartInfo.put("CHECKED", "0");
						}
						
					}
					
					if (name.size()!=0) {
						Integer b = 0;//bname
						for (String n : name) {
//							String[] buName = {n};
//							Map<String, String[]> bName = new HashMap<>();
							Map<String, String> bName = new HashMap<>();
							Map<String, PageData[]> cartIn = new HashMap<>();
//							Map<Map<String, String[]>,  Map<String, PageData[]>> cartListInfo = new HashMap<>();
//							Map<Map<String, String>,  Map<String, PageData[]>> cartListInfo = new HashMap<>();
							int a = 0;//pArr长度
							
//							bName.put("business_name", buName);
							bName.put("business_name", n);
//							logBefore(logger, n);
							for (String nn : nameNum) {
//								logBefore(logger, nn);
								if (nn.equals(n)) {
									a++;
								}
								
							}
							PageData[] pArr = new PageData[a];
				 			String stan = "";
							a=0;
							for (PageData cartInfo : cartList) {
								String shopName = (String) cartInfo.get("SHOPNAME");
								String standId = (String) cartInfo.get("STANDARD_ID");
								if (shopName.equals(n) && !standId.equals(stan)) {
									pArr[a]=cartInfo;
									a++;
								}
								stan=standId;
								
							}
//							cartIn
							cartIn.put("business_arry",pArr);
							Object[] cartInfoList = {bName,cartIn};
//							cartListInfo.put(bName,cartIn);
//							cart.put(b, cartListInfo);
							cart.put(b, cartInfoList);
							b++;
						}
						
					}
					
					map.put("pd", cart);
//					map.put("pd", cartList);
					result = (cart==null)?"02":"01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 动态查询商品的规格id,价格以及库存
	 * @Author zhanglingbing
	 * @date 2018年1月31日
	 * @return
	 *
	 */
	@RequestMapping(value = "/propristo")
	@ResponseBody
	public Object selectStandardIdAndPrice() {
		logBefore(logger, "动态查询商品的规格id,价格以及库存");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("PROPRISTO", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("selectStandardIdAndPrice", pd)) { // 检查参数
					PageData pro = cartInService.selectStandardIdAndPrice(pd);
					map.put("pd", pro);
					result = (null == pro) ? "02" : "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 根据购物车id修改选择状态
	 * @author zhanglingbing
	 * @date 2018年2月2日
	 * @return
	 */
	@RequestMapping(value = "/checkstatus")
	@ResponseBody
	public Object upCartCheckStatus() {
		logBefore(logger, "根据购物车id修改选择状态");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("CHECKSTATUS", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("upCartCheckStatus", pd)) { // 检查参数
					cartInService.updProChecked(pd);
					result = "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
	
	
	/**
	 * 购物车单个信息
	 * @author zhanglingbing
	 * @date 2018年2月26日
	 * @return
	 */
	@RequestMapping(value = "/cartProInfo")
	@ResponseBody
	public Object cartInfo() {
		logBefore(logger, "购物车单个信息");
		
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("CARTINFO", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("cartInfo", pd)) { // 检查参数
					List<PageData> cartInfo = cartInService.selectCartListInfo(pd);
					map.put("pd", cartInfo);
					result = "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}

	
	/**
	 * 购物车数量
	 * @author zhanglingbing
	 * @date 2018年2月26日
	 * @return
	 */
	@RequestMapping(value = "/cartnum")
	@ResponseBody
	public Object cartNumber() {
		logBefore(logger, "购物车数量");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		logBefore(logger, pd.toString());
		try {
			if (Tools.checkKey("CARTNUM", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("cartNumber", pd)) { // 检查参数
					PageData cartNumber = cartInService.selectCartNum(pd);
					map.put("pd", cartNumber);
					result = "01";
				} else {
					result = "03";
				}
			} else {
				result = "05";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
	
	
}
